// src/components/SystemOperations/OperationLog.jsx
import React, { useState, useEffect } from 'react';
import {
  Table, Card, Form, Input, Select, DatePicker,
  Button, Space, Tag, Modal, Descriptions
} from 'antd';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';

const { RangePicker } = DatePicker;
const { Option } = Select;

const OperationLog = () => {
  const [logs, setLogs] = useState([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [queryParams, setQueryParams] = useState({
    page: 1,
    limit: 20,
    username: '',
    module: '',
    action: '',
    status: '',
    startTime: '',
    endTime: ''
  });
  const [form] = Form.useForm();

  // 模拟数据
  const mockLogs = [
    {
      id: 1,
      username: 'admin',
      module: '用户管理',
      action: '新增用户',
      description: '新增用户: testuser',
      requestParams: '{"username":"testuser","email":"test@example.com"}',
      responseResult: '{"code":200,"message":"success"}',
      status: 'success',
      ipAddress: '192.168.1.100',
      userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
      costTime: 120,
      operTime: '2025-09-04 10:30:25'
    },
    {
      id: 2,
      username: 'admin',
      module: '数据源管理',
      action: '删除数据源',
      description: '删除数据源: sales_db',
      requestParams: '{"id":5}',
      responseResult: '{"code":200,"message":"success"}',
      status: 'success',
      ipAddress: '192.168.1.100',
      userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
      costTime: 85,
      operTime: '2025-09-04 09:15:42'
    },
    {
      id: 3,
      username: 'user1',
      module: '内容分发',
      action: '发布任务',
      description: '发布任务: quarterly_report',
      requestParams: '{"contentId":"quarterly_report","targetType":"role"}',
      responseResult: '{"code":500,"message":"发布失败"}',
      status: 'failed',
      ipAddress: '192.168.1.105',
      userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
      costTime: 320,
      operTime: '2025-09-04 08:45:17'
    }
  ];

  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 100,
    },
    {
      title: '操作模块',
      dataIndex: 'module',
      key: 'module',
      width: 120,
    },
    {
      title: '操作类型',
      dataIndex: 'action',
      key: 'action',
      width: 120,
    },
    {
      title: '操作描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: 'IP地址',
      dataIndex: 'ipAddress',
      key: 'ipAddress',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status) => (
        <Tag color={status === 'success' ? 'green' : 'red'}>
          {status === 'success' ? '成功' : '失败'}
        </Tag>
      ),
    },
    {
      title: '耗时(ms)',
      dataIndex: 'costTime',
      key: 'costTime',
      width: 80,
    },
    {
      title: '操作时间',
      dataIndex: 'operTime',
      key: 'operTime',
      width: 150,
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      render: (_, record) => (
        <Button type="link" size="small" onClick={() => showLogDetail(record)}>
          详情
        </Button>
      ),
    },
  ];

  const fetchLogs = async (params = queryParams) => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      setLogs(mockLogs);
      setTotal(mockLogs.length);
      setLoading(false);
    }, 500);
  };

  useEffect(() => {
    fetchLogs();
  }, []);

  const handleSearch = (values) => {
    const params = {
      ...queryParams,
      ...values,
      page: 1,
    };
    setQueryParams(params);
    fetchLogs(params);
  };

  const handleReset = () => {
    form.resetFields();
    const params = {
      page: 1,
      limit: 20,
      username: '',
      module: '',
      action: '',
      status: '',
      startTime: '',
      endTime: ''
    };
    setQueryParams(params);
    fetchLogs(params);
  };

  const handleTableChange = (pagination) => {
    const params = {
      ...queryParams,
      page: pagination.current,
      limit: pagination.pageSize,
    };
    setQueryParams(params);
    fetchLogs(params);
  };

  const showLogDetail = (record) => {
    Modal.info({
      title: '操作日志详情',
      width: 800,
      content: (
        <div>
          <Descriptions column={1} bordered>
            <Descriptions.Item label="用户名">{record.username}</Descriptions.Item>
            <Descriptions.Item label="操作模块">{record.module}</Descriptions.Item>
            <Descriptions.Item label="操作类型">{record.action}</Descriptions.Item>
            <Descriptions.Item label="操作描述">{record.description}</Descriptions.Item>
            <Descriptions.Item label="请求参数">
              <pre style={{ whiteSpace: 'pre-wrap', margin: 0 }}>
                {record.requestParams}
              </pre>
            </Descriptions.Item>
            <Descriptions.Item label="响应结果">
              <pre style={{ whiteSpace: 'pre-wrap', margin: 0 }}>
                {record.responseResult}
              </pre>
            </Descriptions.Item>
            <Descriptions.Item label="IP地址">{record.ipAddress}</Descriptions.Item>
            <Descriptions.Item label="状态">{record.status}</Descriptions.Item>
            <Descriptions.Item label="耗时">{record.costTime}ms</Descriptions.Item>
            <Descriptions.Item label="操作时间">{record.operTime}</Descriptions.Item>
            <Descriptions.Item label="用户代理">{record.userAgent}</Descriptions.Item>
          </Descriptions>
        </div>
      ),
    });
  };

  return (
    <div>
      <Card>
        <Form form={form} layout="inline" onFinish={handleSearch}>
          <Form.Item name="username" label="用户名">
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item name="module" label="操作模块">
            <Input placeholder="请输入模块名称" />
          </Form.Item>
          <Form.Item name="action" label="操作类型">
            <Select placeholder="请选择操作类型" style={{ width: 120 }}>
              <Option value="新增">新增</Option>
              <Option value="修改">修改</Option>
              <Option value="删除">删除</Option>
              <Option value="查询">查询</Option>
              <Option value="登录">登录</Option>
              <Option value="导出">导出</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" style={{ width: 100 }}>
              <Option value="success">成功</Option>
              <Option value="failed">失败</Option>
            </Select>
          </Form.Item>
          <Form.Item name="timeRange" label="操作时间">
            <RangePicker showTime />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button onClick={handleReset} icon={<ReloadOutlined />}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card style={{ marginTop: 16 }}>
        <Table
          columns={columns}
          dataSource={logs}
          rowKey="id"
          loading={loading}
          pagination={{
            current: queryParams.page,
            pageSize: queryParams.limit,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
          onChange={handleTableChange}
        />
      </Card>
    </div>
  );
};

export default OperationLog;
